﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bamboo.Utils
{
    public class CsvSerializer
    {
        public static void ListToCsv<T>(string filename, IEnumerable<T> list, Encoding encoding)
            where T: class
        {
            var fields = SerializeFieldInfo.Parse(typeof(T));
            using (var writer = new StreamWriter(filename, false, encoding, 128 * 1024))
            {
                bool first = true;
                //写表头
                foreach (var item in fields)
                {
                    if (first) first = false; else writer.Write(",");
                    writer.Write(item.Name());
                }
                writer.Write("\r\n");
                //写数据
                foreach (var item in list)
                {
                    first = true;
                    foreach (var field in fields)
                    {
                        if (first) first = false; else writer.Write(",");
                        object value = field.GetValue(item);
                        if (value != null) writer.Write(value.ToString());
                    }
                    writer.Write("\r\n");
                }
            }
        }

        public static void CsvToList<T>(string filename, IList<T> list, Encoding encoding)
            where T : class, new()
        {
            var fields = SerializeFieldInfo.Parse(typeof(T));
            SerializeFieldInfo[] fieldArray;
            using (var reader = new StreamReader(filename, encoding))
            {
                //解析表头
                {
                    var firstLine = reader.ReadLine();
                    var parts = firstLine.Split(',');
                    fieldArray = new SerializeFieldInfo[parts.Length];
                    for (int i = 0; i < parts.Length; ++i)
                    {
                        string fieldName = parts[i];
                        var field = fields.Find(a => a.Name() == fieldName);
                        fieldArray[i] = field;
                    }
                }
                //解析表数据
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var parts = line.Split(',');
                    var obj = new T();
                    for (int i = 0; i < parts.Length; ++i)
                    {
                        var field = fieldArray[i];
                        if (field == null) continue;
                        field.SetText(obj, parts[i]);
                    }
                    list.Add(obj);
                }
            }
        }
    }
}
